package com.zidongxiangxi.sharding.job.core.listener;

import com.zidongxiangxi.sharding.job.core.ShardingJob;
import com.zidongxiangxi.sharding.job.core.ShardingJobRegistry;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;

/**
 * 注册中心连接状态变化监听
 *
 * @author chenxudong
 * @date 2021/02/19
 */
public class RegistryCenterConnectionStateListener implements ConnectionStateListener {
    private final ShardingJob job;

    public RegistryCenterConnectionStateListener(final ShardingJob job) {
        this.job = job;
    }

    @Override
    public void stateChanged(CuratorFramework curatorFramework, ConnectionState newState) {
        if (ShardingJobRegistry.getInstance().isShutdown(job.getJobName())) {
            return;
        }
        if (ConnectionState.SUSPENDED == newState || ConnectionState.LOST == newState) {
            job.pause();
        } else if (ConnectionState.RECONNECTED == newState) {
            job.getInstancesNode().persistLocalInstanceOnline();
            job.clearRunningInfo();
            job.resume();
        }
    }
}
